All files / web/src/app/remote-camera/[sessionId] page.tsx

0% Statements 0/734
0% Branches 0/1
0% Functions 0/1
0% Lines 0/734

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use client'

import { useParams } from 'next/navigation'
import { useCallback, useEffect, useRef, useState } from 'react'
import { VisionCameraFeed } from '@/components/vision/VisionCameraFeed'
import { usePhoneCamera } from '@/hooks/usePhoneCamera'
import { useRemoteCameraPhone } from '@/hooks/useRemoteCameraPhone'
import { detectMarkers, initArucoDetector, loadAruco } from '@/lib/vision/arucoDetection'
import type { CalibrationGrid } from '@/types/vision'
import { css } from '../../../../styled-system/css'

type ConnectionStatus = 'connecting' | 'connected' | 'error' | 'expired'

/**
 * Phone Camera Page
 *
 * Accessed by scanning QR code on desktop.
 * Starts streaming immediately, auto-detects ArUco markers for cropping.
 * Desktop can override with manual calibration.
 */
export default function RemoteCameraPage() {
  const params = useParams<{ sessionId: string }>()
  const sessionId = params.sessionId

  // Session validation state
  const [sessionStatus, setSessionStatus] = useState<ConnectionStatus>('connecting')
  const [sessionError, setSessionError] = useState<string | null>(null)

  // Camera state - defaults to back camera (environment)
  const {
    isLoading: isCameraLoading,
    error: cameraError,
    stream: videoStream,
    facingMode,
    isTorchOn,
    isTorchAvailable,
    availableDevices,
    start: startCamera,
    stop: stopCamera,
    flipCamera,
    toggleTorch,
    setTorch,
  } = usePhoneCamera({ initialFacingMode: 'environment' })

  // Handler for when desktop requests a mode change - defined before hook call
  // This is called BEFORE the React state updates, so we can set the ref immediately
  // to prevent the race condition in the detection loop
  const desktopIsCalibratingRef = useRef(false)
  // NOTE: We use a ref to hold the state setter to avoid recreating the callback
  const setDesktopIsCalibratingRef = useRef<(v: boolean) => void>(() => {})
  const handleDesktopSetMode = useCallback((mode: 'raw' | 'cropped') => {
    if (mode === 'raw') {
      // Desktop requested raw mode - they're calibrating
      // Set the ref IMMEDIATELY so detection loop sees it right away
      desktopIsCalibratingRef.current = true
      // Also set the state for UI (this is async but that's OK for UI)
      setDesktopIsCalibratingRef.current(true)
    }
  }, [])

  // Remote camera connection - pass setTorch for desktop control
  const {
    isConnected,
    isSending,
    frameMode,
    desktopCalibration,
    desktopColumnCount,
    error: connectionError,
    connect,
    disconnect,
    startSending,
    stopSending,
    updateCalibration,
    setFrameMode,
    emitTorchState,
    setDetectedCorners,
    captureAndSendRawFrame,
    captureAndSendCroppedPreviewFrame,
  } = useRemoteCameraPhone({
    onTorchRequest: setTorch,
    onDesktopSetMode: handleDesktopSetMode,
  })

  // Auto-detection state
  const [calibration, setCalibration] = useState<CalibrationGrid | null>(null)
  const [markersDetected, setMarkersDetected] = useState(0)
  const [arucoReady, setArucoReady] = useState(false)
  const [isVideoReady, setIsVideoReady] = useState(false)

  // Track if we're using desktop calibration (to show in UI)
  const [usingDesktopCalibration, setUsingDesktopCalibration] = useState(false)

  // Track if desktop is actively calibrating (has requested raw mode)
  // When true, we don't auto-switch to cropped even if markers are detected
  // State is used for UI, the ref (defined above) is used in the detection loop
  // to avoid race conditions
  const [desktopIsCalibrating, setDesktopIsCalibrating] = useState(false)
  // Connect the state setter ref so the callback can update state
  setDesktopIsCalibratingRef.current = setDesktopIsCalibrating

  // Track previous frame mode to detect changes (not just initial state)
  const prevFrameModeRef = useRef<typeof frameMode | null>(null)

  // Video element ref
  const videoRef = useRef<HTMLVideoElement | null>(null)

  // Rate limiter for training data capture (separate from regular frame sending)
  // We capture raw frames with corners for boundary detector training at 200ms intervals
  const lastTrainingCaptureRef = useRef<number>(0)
  const TRAINING_CAPTURE_INTERVAL_MS = 200

  // Rate limiter for cropped preview capture during calibration
  // Capture cropped previews at 100ms intervals (10fps) to show in desktop preview
  const lastPreviewCaptureRef = useRef<number>(0)
  const PREVIEW_CAPTURE_INTERVAL_MS = 100

  // Refs for cleanup functions (to avoid stale closures in unmount effect)
  const stopSendingRef = useRef(stopSending)
  const disconnectRef = useRef(disconnect)
  const stopCameraRef = useRef(stopCamera)

  // Keep refs in sync
  useEffect(() => {
    stopSendingRef.current = stopSending
    disconnectRef.current = disconnect
    stopCameraRef.current = stopCamera
  }, [stopSending, disconnect, stopCamera])

  // Keep desktopIsCalibratingRef in sync with state
  useEffect(() => {
    desktopIsCalibratingRef.current = desktopIsCalibrating
  }, [desktopIsCalibrating])

  // Validate session on mount
  useEffect(() => {
    async function validateSession() {
      console.log('[RemoteCameraPage] Validating session:', sessionId)
      try {
        const response = await fetch(`/api/remote-camera?sessionId=${sessionId}`)
        console.log('[RemoteCameraPage] Session validation response:', response.status)
        if (response.ok) {
          const data = await response.json()
          console.log('[RemoteCameraPage] Session valid:', data)
          setSessionStatus('connected')
        } else if (response.status === 404) {
          setSessionStatus('expired')
          setSessionError('Session not found or expired')
        } else {
          setSessionStatus('error')
          const data = await response.json()
          setSessionError(data.error || 'Failed to validate session')
        }
      } catch (err) {
        console.error('[RemoteCameraPage] Session validation error:', err)
        setSessionStatus('error')
        setSessionError('Network error')
      }
    }

    validateSession()
  }, [sessionId])

  // Load ArUco library
  useEffect(() => {
    loadAruco()
      .then(() => {
        initArucoDetector()
        setArucoReady(true)
      })
      .catch((err) => {
        console.error('Failed to load ArUco:', err)
      })
  }, [])

  // Connect to session when validated
  useEffect(() => {
    if (sessionStatus === 'connected' && !isConnected) {
      connect(sessionId)
    }
  }, [sessionStatus, isConnected, sessionId, connect])

  // Request camera when connected
  useEffect(() => {
    if (isConnected && !videoStream && !isCameraLoading) {
      startCamera()
    }
  }, [isConnected, videoStream, isCameraLoading, startCamera])

  // Emit torch state to desktop when it changes or when connected
  useEffect(() => {
    if (isConnected) {
      emitTorchState(isTorchOn, isTorchAvailable)
    }
  }, [isConnected, isTorchOn, isTorchAvailable, emitTorchState])

  // Handle video ready - start sending immediately
  const handleVideoReady = useCallback(
    (width: number, height: number) => {
      setIsVideoReady(true)
      // Start sending as soon as video is ready
      if (isConnected && videoRef.current && !isSending) {
        startSending(videoRef.current)
      }
    },
    [isConnected, isSending, startSending]
  )

  // Also try to start sending when connection is established (if video already ready)
  useEffect(() => {
    if (isConnected && isVideoReady && videoRef.current && !isSending) {
      startSending(videoRef.current)
    }
  }, [isConnected, isVideoReady, isSending, startSending])

  // Sync desktop calibration to local state
  useEffect(() => {
    if (desktopCalibration) {
      // Use column count from desktop, fallback to 13 (standard soroban)
      const cols = desktopColumnCount ?? 13
      const grid: CalibrationGrid = {
        roi: {
          x: Math.min(desktopCalibration.topLeft.x, desktopCalibration.bottomLeft.x),
          y: Math.min(desktopCalibration.topLeft.y, desktopCalibration.topRight.y),
          width:
            Math.max(desktopCalibration.topRight.x, desktopCalibration.bottomRight.x) -
            Math.min(desktopCalibration.topLeft.x, desktopCalibration.bottomLeft.x),
          height:
            Math.max(desktopCalibration.bottomLeft.y, desktopCalibration.bottomRight.y) -
            Math.min(desktopCalibration.topLeft.y, desktopCalibration.topRight.y),
        },
        corners: desktopCalibration,
        columnCount: cols,
        columnDividers: Array.from({ length: cols - 1 }, (_, i) => (i + 1) / cols),
        rotation: 0,
      }
      setCalibration(grid)
      // Only mark as "using desktop calibration" when calibration is COMPLETE.
      // Preview calibrations keep the phone in raw mode - we're still calibrating.
      // This allows the detection loop to keep running and send cropped previews.
      if (frameMode === 'cropped') {
        setUsingDesktopCalibration(true)
        setDesktopIsCalibrating(false)
        desktopIsCalibratingRef.current = false
      }
      // Update the calibration for the sending loop
      if (isSending) {
        updateCalibration(desktopCalibration)
      }
    } else if (usingDesktopCalibration) {
      // Desktop cleared calibration - go back to auto-detection
      setUsingDesktopCalibration(false)
      setCalibration(null)
    }
  }, [
    desktopCalibration,
    desktopColumnCount,
    frameMode,
    isSending,
    updateCalibration,
    usingDesktopCalibration,
  ])

  // Auto-detect markers (always runs unless using desktop calibration)
  useEffect(() => {
    // Don't run auto-detection if using desktop calibration
    if (usingDesktopCalibration) return
    if (!videoStream || !arucoReady || !videoRef.current) return

    const video = videoRef.current
    let animationId: number

    const detectLoop = () => {
      if (video.readyState >= 2) {
        const result = detectMarkers(video)
        setMarkersDetected(result.markersFound)

        if (result.allMarkersFound && result.quadCorners) {
          // Auto-calibration successful!
          // NOTE: detectMarkers() returns corners swapped for Desk View camera (180° rotated).
          // Phone camera is NOT Desk View, so we need to swap corners back to get correct orientation.
          // detectMarkers maps: marker 2 (physical BR) → topLeft, marker 0 (physical TL) → bottomRight
          // For phone camera we need: marker 0 (physical TL) → topLeft, marker 2 (physical BR) → bottomRight
          const phoneCorners = {
            topLeft: result.quadCorners.bottomRight, // marker 0 (physical TL)
            topRight: result.quadCorners.bottomLeft, // marker 1 (physical TR)
            bottomRight: result.quadCorners.topLeft, // marker 2 (physical BR)
            bottomLeft: result.quadCorners.topRight, // marker 3 (physical BL)
          }
          console.log('[PHONE] Markers detected! phoneCorners:', JSON.stringify(phoneCorners))
          console.log('[PHONE] desktopIsCalibratingRef.current:', desktopIsCalibratingRef.current)
          console.log('[PHONE] isSending:', isSending, 'frameMode:', frameMode)
          const grid: CalibrationGrid = {
            roi: {
              x: Math.min(phoneCorners.topLeft.x, phoneCorners.bottomLeft.x),
              y: Math.min(phoneCorners.topLeft.y, phoneCorners.topRight.y),
              width:
                Math.max(phoneCorners.topRight.x, phoneCorners.bottomRight.x) -
                Math.min(phoneCorners.topLeft.x, phoneCorners.bottomLeft.x),
              height:
                Math.max(phoneCorners.bottomLeft.y, phoneCorners.bottomRight.y) -
                Math.min(phoneCorners.topLeft.y, phoneCorners.topRight.y),
            },
            corners: phoneCorners,
            columnCount: 13,
            columnDividers: Array.from({ length: 12 }, (_, i) => (i + 1) / 13),
            rotation: 0,
          }
          setCalibration(grid)

          // When desktop is calibrating (raw mode), capture and send frame atomically
          // This ensures the corners and frame are from the exact same video frame
          if (desktopIsCalibratingRef.current && isSending) {
            console.log('[PHONE] Desktop calibrating - capturing atomic frame+corners')
            captureAndSendRawFrame(video, phoneCorners)

            // Also send cropped preview frame if desktop has sent calibration corners
            // Rate-limited to 100ms intervals (10fps) to avoid overwhelming socket
            if (desktopCalibration) {
              const now = performance.now()
              if (now - lastPreviewCaptureRef.current >= PREVIEW_CAPTURE_INTERVAL_MS) {
                lastPreviewCaptureRef.current = now
                console.log('[PHONE] Desktop calibrating - also capturing cropped preview')
                captureAndSendCroppedPreviewFrame(video, desktopCalibration)
              }
            }
          } else {
            // Normal mode: just store corners for the regular capture loop
            console.log('[PHONE] Calling setDetectedCorners with phoneCorners')
            setDetectedCorners(phoneCorners)

            // TRAINING DATA CAPTURE: Also send raw frames for boundary detector training
            // Rate-limited to 200ms intervals (5fps) - not every detection frame
            if (isSending) {
              const now = performance.now()
              if (now - lastTrainingCaptureRef.current >= TRAINING_CAPTURE_INTERVAL_MS) {
                lastTrainingCaptureRef.current = now
                captureAndSendRawFrame(video, phoneCorners)
              }
            }
          }

          // Update the calibration for the sending loop and switch to cropped mode
          // BUT: don't switch to cropped if desktop is actively calibrating (they need raw frames)
          // CRITICAL: Use the ref, not state, to avoid race conditions. The ref is updated
          // immediately when desktop requests raw mode, while state updates asynchronously.
          if (isSending && !desktopIsCalibratingRef.current) {
            updateCalibration(phoneCorners)
            setFrameMode('cropped')
          }
        } else {
          // No markers found - clear detected corners so desktop knows
          setDetectedCorners(null)

          // Even without markers, send cropped preview if desktop is calibrating
          // Rate-limited to 100ms intervals (10fps)
          if (desktopIsCalibratingRef.current && isSending && desktopCalibration) {
            const now = performance.now()
            if (now - lastPreviewCaptureRef.current >= PREVIEW_CAPTURE_INTERVAL_MS) {
              lastPreviewCaptureRef.current = now
              console.log(
                '[PHONE] No markers but desktop has calibration - sending cropped preview'
              )
              captureAndSendCroppedPreviewFrame(video, desktopCalibration)
            }
          }
        }
        // Note: We intentionally do NOT clear calibration when markers are lost.
        // Once calibration is set, it persists until:
        // 1. New markers are detected (updates calibration)
        // 2. Desktop sends a new calibration (override)
        // 3. Desktop requests raw mode (for manual recalibration)
      }

      animationId = requestAnimationFrame(detectLoop)
    }

    detectLoop()

    return () => {
      if (animationId) cancelAnimationFrame(animationId)
    }
  }, [
    videoStream,
    arucoReady,
    isSending,
    updateCalibration,
    setFrameMode,
    usingDesktopCalibration,
    setDetectedCorners,
    captureAndSendRawFrame,
    captureAndSendCroppedPreviewFrame,
    desktopCalibration,
    // NOTE: desktopIsCalibrating state was removed from deps - we use the ref instead
    // to avoid race conditions. The ref (desktopIsCalibratingRef) is accessed directly
    // in the loop and is updated immediately when desktop requests raw mode.
  ])

  // When frameMode CHANGES to 'raw' from 'cropped', mark desktop as calibrating
  // This prevents auto-switching back to cropped when markers are detected
  // We check prevFrameModeRef to avoid triggering on initial render
  useEffect(() => {
    const prevMode = prevFrameModeRef.current
    prevFrameModeRef.current = frameMode

    // Only trigger when changing from cropped to raw (not on initial load)
    if (frameMode === 'raw' && prevMode === 'cropped') {
      // Desktop requested raw mode - they're calibrating
      setDesktopIsCalibrating(true)
      desktopIsCalibratingRef.current = true
      if (usingDesktopCalibration) {
        setUsingDesktopCalibration(false)
        setCalibration(null)
      }
    }
  }, [frameMode, usingDesktopCalibration])

  // Cleanup on unmount only (use refs to avoid stale closures)
  useEffect(() => {
    return () => {
      stopSendingRef.current()
      disconnectRef.current()
      stopCameraRef.current()
    }
  }, [])

  // Render based on session status
  if (sessionStatus === 'connecting') {
    return (
      <div
        className={css({
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          bg: 'gray.900',
          color: 'white',
        })}
      >
        <div className={css({ textAlign: 'center' })}>
          <div
            className={css({
              width: 10,
              height: 10,
              border: '3px solid',
              borderColor: 'gray.600',
              borderTopColor: 'blue.400',
              borderRadius: 'full',
              mx: 'auto',
              mb: 4,
            })}
            style={{ animation: 'spin 1s linear infinite' }}
          />
          <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
          <p>Connecting to session...</p>
        </div>
      </div>
    )
  }

  if (sessionStatus === 'expired' || sessionStatus === 'error') {
    return (
      <div
        className={css({
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          bg: 'gray.900',
          color: 'white',
          px: 4,
        })}
      >
        <div className={css({ textAlign: 'center', maxWidth: '400px' })}>
          <div className={css({ fontSize: '4xl', mb: 4 })}>
            {sessionStatus === 'expired' ? '⏰' : '❌'}
          </div>
          <h1 className={css({ fontSize: 'xl', fontWeight: 'bold', mb: 2 })}>
            {sessionStatus === 'expired' ? 'Session Expired' : 'Connection Error'}
          </h1>
          <p className={css({ color: 'gray.400', mb: 4 })}>
            {sessionError || 'Please scan the QR code again on your desktop.'}
          </p>
        </div>
      </div>
    )
  }

  return (
    <div
      className={css({
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        bg: 'gray.900',
        color: 'white',
      })}
      data-component="remote-camera-page"
    >
      {/* Header */}
      <header
        className={css({
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 4,
          py: 3,
          borderBottom: '1px solid',
          borderColor: 'gray.800',
        })}
      >
        <h1 className={css({ fontSize: 'lg', fontWeight: 'semibold' })}>Remote Camera</h1>
        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 3,
          })}
        >
          {/* Camera controls */}
          {videoStream && (
            <div
              className={css({
                display: 'flex',
                alignItems: 'center',
                gap: 2,
              })}
            >
              {/* Flip camera button - only show if multiple cameras available */}
              {availableDevices.length > 1 && (
                <button
                  type="button"
                  onClick={flipCamera}
                  className={css({
                    p: 2,
                    bg: 'gray.700',
                    borderRadius: 'full',
                    border: 'none',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    _hover: { bg: 'gray.600' },
                  })}
                  title={`Switch to ${facingMode === 'environment' ? 'front' : 'back'} camera`}
                  data-action="flip-camera"
                >
                  <svg
                    width="20"
                    height="20"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5" />
                    <path d="M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5" />
                    <circle cx="12" cy="12" r="3" />
                    <path d="m18 22-3-3 3-3" />
                    <path d="m6 2 3 3-3 3" />
                  </svg>
                </button>
              )}

              {/* Torch button - only show if available */}
              {isTorchAvailable && (
                <button
                  type="button"
                  onClick={toggleTorch}
                  className={css({
                    p: 2,
                    bg: isTorchOn ? 'yellow.500' : 'gray.700',
                    borderRadius: 'full',
                    border: 'none',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: isTorchOn ? 'gray.900' : 'white',
                    _hover: { bg: isTorchOn ? 'yellow.400' : 'gray.600' },
                  })}
                  title={isTorchOn ? 'Turn off flash' : 'Turn on flash'}
                  data-action="toggle-torch"
                >
                  <svg
                    width="20"
                    height="20"
                    viewBox="0 0 24 24"
                    fill={isTorchOn ? 'currentColor' : 'none'}
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
                  </svg>
                </button>
              )}
            </div>
          )}

          {/* Status indicator */}
          <div
            className={css({
              display: 'flex',
              alignItems: 'center',
              gap: 2,
              fontSize: 'sm',
            })}
          >
            <span
              className={css({
                width: 2,
                height: 2,
                borderRadius: 'full',
                bg: isConnected ? (isSending ? 'green.500' : 'yellow.500') : 'red.500',
              })}
            />
            <span className={css({ color: 'gray.400' })}>
              {isConnected
                ? isSending
                  ? frameMode === 'raw'
                    ? 'Streaming (Raw)'
                    : 'Streaming (Cropped)'
                  : 'Connected'
                : 'Connecting...'}
            </span>
          </div>
        </div>
      </header>

      {/* Camera Feed */}
      <div
        className={css({
          flex: 1,
          position: 'relative',
          minHeight: '300px',
        })}
      >
        <VisionCameraFeed
          videoStream={videoStream}
          isLoading={isCameraLoading}
          calibration={calibration}
          showCalibrationGrid={!!calibration}
          videoRef={(el) => {
            videoRef.current = el
          }}
          onVideoReady={handleVideoReady}
        />

        {/* Camera error overlay */}
        {cameraError && (
          <div
            className={css({
              position: 'absolute',
              inset: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bg: 'rgba(0, 0, 0, 0.8)',
              p: 4,
            })}
          >
            <div className={css({ textAlign: 'center' })}>
              <p className={css({ color: 'red.400', mb: 4 })}>{cameraError}</p>
              <button
                type="button"
                onClick={() => startCamera()}
                className={css({
                  px: 4,
                  py: 2,
                  bg: 'blue.600',
                  color: 'white',
                  borderRadius: 'lg',
                  fontWeight: 'medium',
                  border: 'none',
                  cursor: 'pointer',
                })}
              >
                Retry Camera
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Status Footer */}
      <div
        className={css({
          px: 4,
          py: 3,
          borderTop: '1px solid',
          borderColor: 'gray.800',
        })}
      >
        {/* Marker detection status */}
        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 2,
            p: 3,
            bg: 'gray.800',
            borderRadius: 'lg',
          })}
        >
          <span className={css({ fontSize: 'lg' })}>
            {usingDesktopCalibration ? '🎯' : markersDetected === 4 ? '✅' : '🔍'}
          </span>
          <div>
            <p className={css({ fontWeight: 'medium' })}>
              {usingDesktopCalibration
                ? 'Using Desktop Calibration'
                : `${markersDetected}/4 Markers Detected`}
            </p>
            <p className={css({ fontSize: 'sm', color: 'gray.400' })}>
              {usingDesktopCalibration
                ? 'Cropping set by desktop'
                : calibration
                  ? 'Auto-cropping active'
                  : 'Point camera at abacus markers'}
            </p>
          </div>
        </div>

        {/* Connection error */}
        {connectionError && (
          <p className={css({ color: 'red.400', fontSize: 'sm', mt: 2 })}>{connectionError}</p>
        )}
      </div>
    </div>
  )
}